package controllers

import (
	"go_server/models/req"
	"go_server/service"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 添加用户
func UserAdd(c *gin.Context) {
	var user req.UserLoginOrAdd
	if c.ShouldBind(&user) == nil {
		if service.UserAdd(&user) {
			c.JSON(http.StatusOK, gin.H{
				"msg": "添加成功",
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"msg": "账号已存在",
			})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "参数不正确",
		})
	}
}

// 修改用户密码
func UserSetPassword(c *gin.Context) {
	var data req.UserSetPassworder
	if c.ShouldBind(&data) == nil {
		res := service.UserSetPassword(&data)
		if res {
			c.JSON(http.StatusOK, gin.H{
				"msg": "修改成功",
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"msg": "用户名或原密码不正确",
			})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "参数不正确",
		})
	}
}

func UserFind(c *gin.Context) {
	page, _ := strconv.ParseInt(c.Query("page"), 10, 64)
	size, _ := strconv.ParseInt(c.Query("size"), 10, 64)
	res, total := service.UserFind(page, size)
	c.JSON(http.StatusOK, gin.H{
		"msg":   "查询成功",
		"data":  res,
		"total": total,
	})
}

func Del(c *gin.Context) {
	var user req.UserLoginOrAdd
	if c.ShouldBind(&user) == nil {
		res := service.UserDel(&user)
		if res {
			c.JSON(http.StatusOK, gin.H{
				"msg": "删除成功",
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"msg": "用户名或密码不正确",
			})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "参数不正确",
		})
	}
}
